<template>
  <div class="con">
    <div class="video-container">
      <video
        id="remoteVideo"
        width="100%"
        height="100%"
        autoplay="autoplay"
        style="border: 1px solid #000000"
      ></video>
    </div>
    <div class="floating-button">
      <el-button
          type="primary"
          :icon="Share"
          circle
          @click="startvideo()"
      />
    </div>
  </div>
</template>

<script setup>
import {
  Link,
  Delete,
  Edit,
  Message,
  Plus,
  Share,
} from '@element-plus/icons-vue'
import { reactive, ref, onMounted } from 'vue'
import { isMyCourse } from '../api/course'
import { useRoute, useRouter } from 'vue-router'
import { useStaffStore } from '../stores/staff'

const env = import.meta.env
const socketurl = env['VITE_SOCKET_URL']

const handleClick = (tab, event) => {
  console.log(tab, event)
}

const staffStore = useStaffStore()
const username = staffStore.username;
//const payload = JSON.parse(tname);
//const username = payload.username;
console.log("livestu username ---------> "+username);
const route = useRoute()
const currentRoute = useRouter()
const courseid = route.query.courseid
const lessionid = route.query.lessionid

const TYPE_COMMAND_ROOM_ENTER = "enterRoom";
const TYPE_COMMAND_ROOM_LIST = "roomList";
const TYPE_COMMAND_DIALOGUE = "dialogue";
const TYPE_COMMAND_READY = "ready";
const TYPE_COMMAND_OFFER = "offer";
const TYPE_COMMAND_ANSWER = "answer";
const TYPE_COMMAND_CANDIDATE = "candidate";

let iceServers = {
  "iceServers": [
    { "url": "stun:stun.services.mozilla.com" },
    { "url": "stun:stun.l.google.com:19302" }
  ]
};

const offerOptions = {
  iceRestart: true,
  offerToReceiveAudio: false, //true,由于没有麦克风，所有如果请求音频，会报错，不过不会影响视频流播放
  offerToReceiveVideo: true
};

let websocket
let localMediaStream
let rtcPeerConnection;

const lessiondata = reactive({
  list: [],
  isMyCourse: false
})

onMounted(() => {
  loaddata();
})

function loaddata () {
  initsocket();
}

const handleMessage = (event) => {
  let message = JSON.parse(event.data);
  switch (message.command) {
    case TYPE_COMMAND_ROOM_ENTER://进入房间，然后打开本地共享桌面流媒体
      if (message.message === "joined") {
        //roomId = message.roomId;
        //  openLocalMedia()
        //      .then(() => {
        //          websocket.send(JSON.stringify({command: TYPE_COMMAND_READY, userId: userId, roomId: roomId}));
        //      })
        //      .catch(() => {
        //      })
        websocket.send(JSON.stringify({ command: TYPE_COMMAND_READY, username: username, roomId: lessionid }));
      }
      // else
      // {
      //     //caller = true;
      //     openLocalMedia()
      //         .then(() => {})
      //         .catch(() => {});
      // }

      break;
    case TYPE_COMMAND_ROOM_LIST:
      break;
    case TYPE_COMMAND_DIALOGUE:
      break;
    case TYPE_COMMAND_READY:

      if (!rtcPeerConnection) {
        rtcPeerConnection = new RTCPeerConnection(iceServers);
        rtcPeerConnection.onicecandidate = onIceCandidate;
        rtcPeerConnection.ontrack = onTrack;
      }

      let sdpMessage1 = message.message;
      sdpMessage1 = sdpMessage1.replace(/[\r]/g, "\\r").replace(/[\n]/g, "\\n");
      let sdp1 = JSON.parse(sdpMessage1).sdp;

      rtcPeerConnection.setRemoteDescription(new RTCSessionDescription(sdp1))
          .then(() => rtcPeerConnection.createAnswer(offerOptions))
          .then(answer => setLocalAndAnswer(answer))
          .catch(console.error);

        //初始化一个webrtc端点
        // if (!rtcPeerConnection) {
        //   rtcPeerConnection = new RTCPeerConnection(iceServers);
        //   //添加事件监听函数
        //   rtcPeerConnection.onicecandidate = onIceCandidate;
        //   rtcPeerConnection.ontrack = onTrack;
        // }
        // rtcPeerConnection.createOffer(offerOptions)
        //   .then(
        //     setLocalAndOffer
        //   )
        //   .catch(() => {
        //   }
        //   );

      break;
    case TYPE_COMMAND_OFFER:
      // if (!caller)
      {
        //初始化一个webrtc端点
        if (!rtcPeerConnection) {
          rtcPeerConnection = new RTCPeerConnection(iceServers);
          //添加事件监听函数
          rtcPeerConnection.onicecandidate = onIceCandidate;

          rtcPeerConnection.ontrack = onTrack;
        }

        //rtcPeerConnection.addTrack(localMediaStream);

        // for (const track of localMediaStream.getTracks()) {
        //     rtcPeerConnection.addTrack(track, localMediaStream);
        // }

        //原因：后端接口返回的数据换行采用了\r\n方式，使得json文本无法解析带换行符的内容
        //解决方法：将Json字符串中所有的\r\n转成\\r\\n
        let sdpMessage = message.message;
        sdpMessage.replace(/[\r]/g, "\\r").replace(/[\n]/g, "\\n");
        console.log(sdpMessage);
        let sdp = JSON.parse(sdpMessage).sdp;
        rtcPeerConnection.setRemoteDescription(new RTCSessionDescription(sdp))
          .then(
        );
        rtcPeerConnection.createAnswer(offerOptions)
          .then(
            setLocalAndAnswer
          )
          .catch(() => {
          }
          );
      }
      break;
    case TYPE_COMMAND_ANSWER:
      //原因：后端接口返回的数据换行采用了\r\n方式，使得json文本无法解析带换行符的内容
      //解决方法：将Json字符串中所有的\r\n转成\\r\\n
      let sdpMessage = message.message;
      sdpMessage.replace(/[\r]/g, "\\r").replace(/[\n]/g, "\\n");
      console.log(sdpMessage);
      let sdp = JSON.parse(sdpMessage).sdp;
      rtcPeerConnection.setRemoteDescription(new RTCSessionDescription(sdp)).then(
        console.log("setRemoteDescription 完毕")
        );
      break;
    case TYPE_COMMAND_CANDIDATE:
      let candidateMessage = message.message;
      //console.log(candidateMessage);
      let candidate = JSON.parse(candidateMessage).candidate;
      let rtcIceCandidate = new RTCIceCandidate({
        sdpMid: candidate.sdpMid,
        sdpMLineIndex: candidate.label,
        candidate: candidate.candidate
      });
      rtcPeerConnection.addIceCandidate(rtcIceCandidate)
        .then(
        //log("addIceCandidate 完毕")
      );
      break;
  }
};

const onTrack = (event) => {
  let remoteMediaStream = event.streams[0];
  let remoteVideo = document.getElementById("remoteVideo");
  remoteVideo.srcObject = remoteMediaStream;
  remoteVideo.play();
};

const onIceCandidate = (event) => {
  if (event.candidate) {
    //log("sending ice candidate");
    websocket.send(JSON.stringify({
      command: TYPE_COMMAND_CANDIDATE,
      username: username,
      roomId: lessionid,
      message: {
        candidate: {
          sdpMid: event.candidate.sdpMid,
          sdpMLineIndex: event.candidate.sdpMLineIndex,
          candidate: event.candidate.candidate
        }
      }
    }));

  }
};

const setLocalAndOffer = (sessionDescription) => {
  rtcPeerConnection.setLocalDescription(sessionDescription)
    .then(
    //log("setLocalDescription 完毕")
  );
  websocket.send(
    JSON.stringify({
      command: TYPE_COMMAND_OFFER,
      username: username,
      roomId: lessionid,
      message: {
        sdp: sessionDescription,
      }
    })
  );
};

const setLocalAndAnswer = (sessionDescription) => {
  rtcPeerConnection.setLocalDescription(sessionDescription)
    .then(
    //log("setLocalDescription 完毕")
  );
  websocket.send(
    JSON.stringify({
      command: TYPE_COMMAND_ANSWER,
      username: username,
      roomId: lessionid,
      message: {
        sdp: sessionDescription,
      }
    })
  );
};

//打开本地音视频,用promise这样在打开视频成功后，再进行下一步操作
// async function openLocalMedia() {
//     videoStream = await navigator.mediaDevices.getDisplayMedia({
//         video: {MediaSource: "screen"},
//     });

//     audioStream = await navigator.mediaDevices.getUserMedia({
//         audio: {
//             sampleSize: 100,
//             frameRate: { max: 30 },
//             noiseSuppression: true,
//             echoCancellation: true,
//             channelCount: 2
//         }
//     });

//     var audioTrack = audioStream.getAudioTracks()[0];

//     videoStream.addTrack(audioTrack);


//     localMediaStream = videoStream;
//     // let localVideo = document.getElementById("localVideo");
//     // localVideo.srcObject = localMediaStream;
//     // localVideo.play();

// }

function initsocket () {

}
//发起共享屏幕的指令
function startvideo () {

  if (!websocket) {
    websocket = new WebSocket(socketurl);
  }
  websocket.onopen = () => {
    //进入到课程lession的直播房间
    websocket.send(JSON.stringify({ command: TYPE_COMMAND_ROOM_ENTER, username: username, roomId: lessionid }));
  };
  websocket.onclose = () => {
    console.log("websocket close");
  };
  websocket.onerror = () => {
    console.log("websocket error");
  };
  websocket.onmessage = handleMessage;
}
</script>

<style lang="less" scoped>
/*.con {
  display: flex;
  height: 100vh;
}*/

.left {
  flex: 2; /* 左边div占据剩余空间的1/3 */
  //background-color: lightblue;
  padding: 10px;
  border-right: 1px solid #000000;
}

.right {
  flex: 1; /* 右边div占据剩余空间的2/3 */
  background-color: lightgrey;
  padding: 10px;
}

.content-panel {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: space-between; /* 左右内容对齐 */
  width: 100%; /* 根据需要调整宽度 */
  padding-top: 10px; /* 根据需要调整内边距 */
}

.content {
  /* 内容样式 */
  margin-left: 5px;
}

.button {
  /* 按钮样式 */
  margin-right: 5px;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.con {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}
.video-container {
  width: 100%;
  height: 100%;
  background-color: #eee;

  video {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}
.floating-button {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 100;

  .el-button {
    background: green;
    width: 40px;
    height: 40px;
    font-size: 24px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}
</style>
